// ==UserScript==
// @name Optimize 163.com in Opera
// @author nanzhi at 12sui.cn
// ==/UserScript==

/**
 * Opera Touch
 * @description opera touch
 */

document.addEventListener('DOMContentLoaded', function() {
	//global var
	var sy, st, ey, et,
		timer,/*settimeout*/
		isStop = false,
		doc = document.documentElement,
		//config option
		t = 1000,
		//animation
		animation = function(time,length) {
			var times = t/time,
				isDown = length < 0,
				abs = Math.abs(length),
				l = abs > 800 ? 100 : (abs > 600 ? 70 : (abs > 300 ? 30 : (abs > 100 ? 15 : 6))),
				_l = isDown ? l : -1*l,
				dvalue = length*(1 + times),
				d = Math.floor(Math.abs(dvalue)/l);

			timer = setTimeout(function() {
				var _top = doc.scrollTop,
					//client height
					cheight = doc.clientHeight,
					//offset height
					oheight = doc.scrollHeight,
					sum = _top + cheight;

				document.addEventListener('click',handle.stopScroll,false);

				if(d < 0 || 
							//top edge
							(_top == 0 && !isDown) || 
							//bottom edge
							((sum > oheight || sum == oheight) && isDown) || isStop) {
					handle.stopScroll();
					return;
				}
				doc.scrollTop = _top + _l;
				d -= 1;
				timer = setTimeout(arguments.callee,1);
			},1);	
		},

		//handle
		handle = {
			//mouse down event
			mdEvent: function(e) {
				sy = e.clientY;
				st = new Date();
			},

			//mouse up event
			muEvent: function(e) {
				ey = e.clientY;
				et = new Date();
				isStop = false;
				handle.scrollPage();
			},

			//scrollPage
			scrollPage:function(arr) {
				var length = ey - sy,
					time = et - st,
					msg = document.getSelection();

				//if select text,return
				if(msg || length === 0) return;

				animation(time,length);
		    },

			//stopScroll
			stopScroll:function() {
				isStop = true;
				timer = null;
				document.removeEventListener('click',handle.stopScroll,false);
		    },

			//event load
			init: function() {
				document.addEventListener('mousedown', handle.mdEvent, false);
				document.addEventListener('mouseup', handle.muEvent, false);
			}

		};
	//excute
	handle.init();
},false);
